<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>部门管理</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css"/>
    <link rel="stylesheet" href="../../../admin/css/other/department.css"/>
    <style>
        .dep {
            margin-top: 3px;
            border: 1px solid;
            border-radius: 4px;
            border-color: #eee;
            flex-grow: 1;
        }

        .layui-anim-downbit {
            background: rgb(236, 236, 236);
            box-shadow: rgba(0, 0, 0, 0.4) 0px 2px 4px, rgba(0, 0, 0, 0.3) 0px 7px 13px -3px, rgba(0, 0, 0, 0.2) 0px -3px 0px inset;
        }

        .layui-menu li {
            border-bottom: 1px solid rgb(236, 236, 236);
        }
        .query {
            display: none;
            padding: 0px 5px;
        }
        .userList .layui-table-cell {
            padding: 0px 10px !important;
        }
        .userList .layui-table-view  {
            margin-top: 0px;
        }
    </style>
</head>
<body class="pear-container">
<div class="query">
    <form class="layui-form" action="">
        <div class="layui-row layui-col-space10">
            <div class="layui-col-md12">
                <div class="layui-card" style="margin-top: 10px;">
                    <div class="layui-card-header">关键字</div>
                    <div class="layui-card-body layui-row layui-col-space10">
                        <div class="layui-col-md12">
                            <input type="text" name="keyword" placeholder="关键字" autocomplete="off"
                                   class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-card" style="margin-top: 10px;">
                    <div class="layui-card-body layui-row layui-col-space10">
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="query">
                            <i class="layui-icon layui-icon-search"></i>
                            查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md">
                            <i class="layui-icon layui-icon-refresh"></i>
                            重置
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<div id="addDepDiv" style="display: none">
    <form class="layui-form layui-form-pane" action="" name="frmMain">

        <div class="mainBox">
            <div class="main-container">
                <div class="layui-form-item ">
                    <label class="layui-form-label">部门名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="dep_name" lay-verify="required" autocomplete="off"
                               placeholder="请输入部门名称"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">部门编号</label>
                    <div class="layui-input-block">
                        <input type="text" name="dep_no" lay-verify="required" autocomplete="off"
                               placeholder="请输入部门名称"
                               class="layui-input">
                    </div>
                </div>
                <input type="hidden" name="pid">
                <input type="hidden" name="dep_name_path_full">
                <input type="hidden" name="dep_id_path_full">
                <input type="hidden" name="company_id">
            </div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                        lay-filter="save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
            </div>
        </div>
    </form>
</div>
<div class="layui-row layui-col-space15">
    <div class="layui-col-md3 layui-col-sm3 layui-col-xl3">
        <div class="layui-card">
            <div class="layui-card-body">
                <div id="department" class="layui-form"
                     style="overflow: auto;height: 93vh;margin-top: 0px;display: flex;flex-flow: column">
                    <div style="height: 40px">
                        <select lay-search="" id="company_list" lay-filter="company_list">
                            <template v-for="(item,index) in company_data">
                                <option selected v-if="item.is_def==1" :value="item.id">{{item.company_name}}</option>
                                <option v-else :value="item.id">{{item.company_name}}</option>
                            </template>
                        </select>
                    </div>
                    <div class="dep">
                        <ul id="dep" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-md9 layui-col-sm9 layui-col-xl9">
        <div class="layui-card">
            <div class="layui-card-body userList" style="height: 93vh">
                <div id="userList" lay-filter="userList" style="">

                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="user-status">
    {{# if(d.status == 1) { }}
    <input type="checkbox" lay-filter="user-status" checked lay-skin="switch" title="启用|锁定">
    {{# }else{ }}
    <input type="checkbox" lay-filter="user-status" lay-skin="switch" title="启用|锁定" readonly>
    {{# } }}
</script>
<script type="text/html" id="user-is_manage">
    {{# if(d.is_manage == 1) { }}
    <input type="checkbox" lay-filter="user-is_manage" checked lay-skin="switch" title="是|否">
    {{# }else{ }}
    <input type="checkbox" lay-filter="user-is_manage" lay-skin="switch" title="是|否" readonly>
    {{# } }}
</script>
<script type="text/html" id="user-is_def">
    {{# if(d.is_def == 1) { }}
    <input type="checkbox" lay-filter="user-is_def" checked lay-skin="switch" title="是|否">
    {{# }else{ }}
    <input type="checkbox" lay-filter="user-is_def" lay-skin="switch" title="是|否" readonly>
    {{# } }}
</script>
<script type="text/html" id="user-userInfo">
    <div style="color: #1e9fff!important">
        <i class="layui-icon layui-icon-username" >{{d.username}}[{{d.nickname}}]</i>
    </div>
</script>
<script type="text/html" id="user-roles">
    {{# if(d.roles.length == 0 ){ }}
    <button class="pear-btn pear-btn-primary pear-btn-xs" lay-event="setRole">
        设置
    </button>
    {{# } else { }}
    {{# let roles = d.roles.map(item=>(item.role_name)).join(" "); }}
    <span style="cursor: pointer;color: #1e9fff" lay-event="setRole">{{roles}}</span>
    {{# } }}
</script>
<script type="text/html" id="user-dep_name_path_full">
    {{d.dep_name_path_full.replaceAll("@@@",">")}}
</script>
<script type="text/html" id="toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="add">
        <i class="layui-icon layui-icon-add-1"></i>
        分配人员
    </button>
    <button class="pear-btn pear-btn-sm" lay-event="sort">
        <i class="layui-icon layui-icon-list"></i>
        排序当前部门人员
    </button>
    <button class="pear-btn pear-btn-danger  pear-btn-sm" lay-event="del">
        <i class="layui-icon layui-icon-delete"></i>
        移除人员
    </button>
    <button class="pear-btn  pear-btn-sm" lay-event="query">
        <i class="layui-icon layui-icon-search"></i>
        查询
    </button>
</script>
<script src="../../../component/vue/vue.global.js"></script>
<script src="../../../config/apiUrl.js"></script>
<script src="../../../component/layui/layui.js"></script>
<script src="../../../component/pear/pear.js"></script>
<script>
    const {createApp, ref} = Vue;
    let company_list = createApp({
        setup() {
            const def_company = ref(0)
            const company_data = ref([])
            return {
                company_data,
                def_company
            }
        },
        updated: function () {
            layui.form.render();
        },
        watch: {
            def_company(newvalue, oldvalue) {
                initTable();
            }
        }

    }).mount('#company_list')
</script>
<script>
    async function intiCompanyList() {
        let list = await layui.common.ajax({
            url: apiUrlConfig.company.getListAll
        })
        for (let datum of list.data) {
            if (datum.is_def == 1) {
                company_list.def_company = datum.id;
            }
        }
        company_list.company_data = list.data;

    }

    function ajaxDataFilter(treeId, parentNode, responseData) {
        for (let datum of responseData.data) {
            datum.dep_name_and_no = `${datum.dep_name}[${datum.dep_no}]`
        }
        if (parentNode == undefined) {
            let company_name = layui.jquery("#company_list").find("option:selected").text();
            responseData.data.unshift({
                id: 0,
                dep_name: company_name,
                isParent: true,
                pid: -1,
                open: true,
                dep_name_and_no: company_name
            })
        }
        return responseData.data;
    }

    /**
     * 加载部门树
     * @param otherParam
     */
    function reloadDeptment(otherParam) {
        var $ = layui.jquery;
        var table = layui.table;
        var toast = layui.toast;
        var common = layui.common;
        var setting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pid",
                    rootPId: -1
                },
                key: {
                    name: "dep_name_and_no"
                }
            },
            edit: {
                enable: true,
                drag: {
                    isCopy: false,
                    isMove: true
                },
                showRemoveBtn: false,
                showRenameBtn: false
            },
            check: {
                enable: true,
                chkStyle: "checkbox",
                chkboxType: {"Y": "s", "N": "s"}
            },
            view: {
                selectedMulti: false
            },
            async: {
                enable: true,
                url: apiUrlConfig.department.getListByPid,
                autoParam: ["id=pid"],
                otherParam: otherParam,
                dataFilter: ajaxDataFilter
            },
            callback: {
                onDrop:async function (
                    event, treeId, treeNodes, targetNode, moveType
                ){
                    var zTree = $.fn.zTree.getZTreeObj(treeId);
                    var paramData = [];
                    var nodeData = [];
                    //子节点拖拽到跟节点 和 根节点的相互排序
                    if (targetNode == null || treeNodes[0].level == 0) {
                        nodeData = zTree.getNodesByParam("level", 0);
                    } else {
                        // 拖拽自己成为子节点
                        var node = zTree.getNodeByTId(treeNodes[0].parentTId);
                        if (node.isParent) {
                            nodeData = zTree.transformToArray(node.children);
                        }
                    }
                    $.each(nodeData, function (i, item) {
                        var dept = {};
                        dept["id"] = item.id;
                        dept["pid"] = item.pid;
                        dept["dep_name"] = item.dep_name;
                        dept["dep_name_path_full"] = item.getPath().map(i=>i.dep_name).join("@@@");
                        dept["dep_id_path_full"] = item.getPath().map(i=>i.id).join("@@@");
                        dept["order_index"] = item.getIndex();//核心：当前节点同级的下标位
                        paramData.push(dept);
                    });
                    //得到这次操作需要变更的数据范围
                    console.log(paramData);
                    let res_data = await common.ajax({
                        url:apiUrlConfig.department.saveOrder,
                        data:JSON.stringify(paramData)
                    })
                    toast.success({title: false, message: '保存成功'})
                },
                beforeDrop: function (treeId, treeNodes, targetNode, moveType) {
                    if(targetNode == null || targetNode.id==0){
                        toast.error({title: false, message: '只能在公司下拖拽'})
                        return false;
                    }
                    console.log(treeId,treeNodes,targetNode,moveType)
                },
                beforeDrag: function (treeId, treeNodes){
                    if(!asyncForAll){
                        toast.error({title: false, message: '请展开所有的部门后排序'})
                        return false;
                    }
                    return true;
                },
                beforeAsync: beforeAsync,
                onAsyncSuccess: onAsyncSuccess,
                onAsyncError: onAsyncError,
                onCheck: function (event, treeId, treeNode) {
                },
                onDblClick: function (event, treeId, treeNode) {
                    if (treeNode.id == 0) {
                        table.reloadData('userList', {
                            where: {
                                company_id: company_list.def_company
                            }
                        }, false)
                    } else {
                        table.reloadData('userList', {
                            where: {
                                company_id: company_list.def_company,
                                dep_id: treeNode.id
                            }
                        }, false)
                    }
                }

            }
        };
        var zTreeObj = $.fn.zTree.init($("#dep"), setting);
    }

    function beforeAsync() {
        curAsyncCount++;
    }

    function onAsyncSuccess(event, treeId, treeNode, msg) {
        curAsyncCount--;
        if (curStatus == "expand") {
            expandNodes(treeNode.children);
        }
        if (curAsyncCount <= 0) {
            if (curStatus != "init" && curStatus != "") {
                asyncForAll = true;
            }
            curStatus = "";
        }
    }

    function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
        curAsyncCount--;
        if (curAsyncCount <= 0) {
            curStatus = "";
            if (treeNode != null) asyncForAll = true;
        }
    }

    var curStatus = "init", curAsyncCount = 0, asyncForAll = false,
        goAsync = false;

    function expandAll() {
        let $ = layui.jquery;
        var zTree = $.fn.zTree.getZTreeObj("dep");
        if (asyncForAll) {
            zTree.expandAll(true);
        } else {
            expandNodes(zTree.getNodes());
            if (!goAsync) {
                curStatus = "";
            }
        }
    }

    function expandNodes(nodes) {
        let $ = layui.jquery;
        if (!nodes) return;
        curStatus = "expand";
        var zTree = $.fn.zTree.getZTreeObj("dep");
        for (var i = 0, l = nodes.length; i < l; i++) {
            zTree.expandNode(nodes[i], true, false, false);
            if (nodes[i].isParent && nodes[i].zAsync) {
                expandNodes(nodes[i].children);
            } else {
                goAsync = true;
            }
        }
    }

    window.edit = function (obj) {
        //获取当前选中的 节点
        let $ = layui.jquery;
        let toast = layui.toast;
        let treeObj = $.fn.zTree.getZTreeObj("dep");
        let nodes = treeObj.getSelectedNodes();
        let select_node = null;
        if (nodes.length > 0) {
            select_node = nodes[0];
        }
        if (select_node.id == 0) {
            toast.error({title: false, message: '不能修改公司，修改请到公司管理'})
            return
        }
        layer.open({
            type: 2,
            title: "修改【" + select_node.dep_name + "】",
            shade: 0.1,
            area: ['50%', '90%'],
            content: 'deptment_update.html?id=' + select_node.id
        });
    }

    window.add = async function () {
        //获取当前选中的 节点
        let $ = layui.jquery;
        let common = layui.jquery;
        let treeObj = $.fn.zTree.getZTreeObj("dep");
        let nodes = treeObj.getSelectedNodes();
        let select_node = null;
        if (nodes.length > 0) {
            select_node = nodes[0];
        }
        let title = "在根目录添加部门";
        if (select_node != null) {
            title = `在【${select_node.dep_name}】下新增部门`;
        }
        layer.open({
            type: 1,
            title: title,
            area: ['50%', '90%'],
            content: $("#addDepDiv")
        });
        frmMain.company_id.value = $("#company_list").val();
        frmMain.dep_name.value = ""
        frmMain.dep_no.value = ""
        if (select_node == null) {
            frmMain.pid.value = 0;
            frmMain.dep_name_path_full.value = ""
            frmMain.dep_id_path_full.value = ""
        } else {
            frmMain.pid.value = select_node.id;
            let nodes = select_node.getPath();
            let nodes_name = [];
            let nodes_id = [];
            for (let node of nodes) {
                nodes_name.push(node.dep_name);
                nodes_id.push(node.id);
            }
            frmMain.dep_name_path_full.value = nodes_name.join("@@@")
            frmMain.dep_id_path_full.value = nodes_id.join("@@@")
        }
    }

    window.expand = function () {
        //获取当前选中的 节点
        let $ = layui.jquery;
        let treeObj = $.fn.zTree.getZTreeObj("dep");
        let nodes = treeObj.getSelectedNodes();
        let select_node = null;
        if (nodes.length > 0) {
            select_node = nodes[0];
        }
        if (select_node != null) {
            expandNodes([select_node]);
        }
    }

    window.fold = function () {
        //获取当前选中的 节点
        let $ = layui.jquery;
        let treeObj = $.fn.zTree.getZTreeObj("dep");
        let nodes = treeObj.getSelectedNodes();
        let select_node = null;
        if (nodes.length > 0) {
            select_node = nodes[0];
        }
        if (select_node != null) {
            treeObj.expandNode(select_node, false, false, true);
        }
    }

    window.del = async function () {
        let $ = layui.jquery;
        let common = layui.common;
        let toast = layui.toast;
        let treeObj = $.fn.zTree.getZTreeObj("dep");
        var nodes = treeObj.getCheckedNodes(true);
        if (nodes.length == 0) {
            toast.error({title: false, message: '请勾选要删除的部门'})
            return
        }
        layer.confirm('确定要删除么（会递归删除部门下所有部门）', {icon: 3, title: '提示'}, async function (index) {
            layer.close(index);
            let res_data = await common.ajax({
                url: apiUrlConfig.department.del,
                data: JSON.stringify(nodes),
                type: "delete"
            })
            toast.success({title: false, message: '删除成功'})
            var node = treeObj.getNodesByParam("id", 0, null);
            if (node.length > 0) {
                treeObj.reAsyncChildNodes(node[0], "refresh", false);
            }
        });

    }

    async function initTable() {
        let $ = layui.jquery;
        let table = layui.table;
        let http = layui.http;
        let form = layui.form;
        let common = layui.common;
        let toast = layui.toast;
        let cols = [
            [
                {
                    type: 'numbers', fixed: "left"
                },
                {
                    type: 'checkbox', fixed: "left"
                },

                {
                    title: '状态',
                    field: 'status',
                    align: 'center',
                    templet: '#user-status', fixed: "left",
                    width: 80
                },
                {
                    title: '管理',
                    field: 'is_manage',
                    align: 'center',
                    templet: '#user-is_manage', fixed: "left",
                    width: 80
                },
                {
                    title: '身份',
                    field: 'is_def',
                    align: 'center',
                    templet: '#user-is_def', fixed: "left",
                    width: 80
                },
                {
                    title: '角色',
                    field: 'roles',
                    align: 'center',
                    templet: '#user-roles', fixed: "left",
                    width: 80
                },
                {
                    title: '账号信息',
                    field: 'userInfo',
                    templet: '#user-userInfo'
                },
                {
                    title: '电话',
                    field: 'telephone',
                    align: 'center',
                },
                {
                    title: '邮箱',
                    field: 'email',
                    align: 'center',
                },
                {
                    title: '所在部门',
                    field: 'userInfo',
                    align: 'center',
                    templet: '#user-dep_name_path_full'
                }
            ]
        ]

        var userTable = table.render({
            contentType: "application/x-www-form-urlencoded",
            height: 'full-30',
            elem: '#userList',
            url: apiUrlConfig.userMapping.getList,
            cellExpandedMode:"tips",
            page: true,
            cols: cols,
            skin: 'grid',
            method: 'post',
            toolbar: '#toolbar',
            limit: 10,
            limits: [10, 50, 100],
            where: {
                company_id: function () {
                    return company_list.def_company
                }
            },
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'limit' //每页数据量的参数名，默认：limit
            },
            headers: {
                "authorization": http.ajax.getToken()
            },
            defaultToolbar: ['filter', 'print', 'exports']
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , response: {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            done: function (res, curr, count) {
                var options = this;
                table.getRowData = function (tableId, elem) {
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };
                form.on('switch(user-status)', async function (obj) {
                    var data = table.getRowData(options.id, obj.elem);
                    console.log(obj.elem.checked, data, "当前行数据");
                    let res_data = await common.ajax({
                        url: apiUrlConfig.user.update,
                        data: JSON.stringify([{
                            id: data.user_id,
                            status: (obj.elem.checked ? 1 : 0),
                            nickname: data.nickname,
                            sex: data.sex
                        }])
                    })
                    toast.success({title: false, message: '修改成功'})
                });

                form.on('switch(user-is_manage)', async function (obj) {
                    var data = table.getRowData(options.id, obj.elem);
                    console.log(obj.elem.checked, data, "当前行数据");
                    try {
                        let res_data = await common.ajax({
                            url: apiUrlConfig.userMapping.updateManageStatus,
                            data: {
                                id: data.id,
                                is_manage: (obj.elem.checked ? 1 : 0),
                            },
                            contentType: 'application/x-www-form-urlencoded'
                        })
                        toast.success({title: false, message: '修改成功'})
                    } catch (e) {
                        toast.error({title: false, message: e.msg})
                    }
                });

                form.on('switch(user-is_def)', async function (obj) {
                    var data = table.getRowData(options.id, obj.elem);
                    console.log(obj.elem.checked, data, "当前行数据");
                    try {
                        let res_data = await common.ajax({
                            url: apiUrlConfig.userMapping.updateDefStatus,
                            data: {
                                id: data.id,
                                user_id: data.user_id,
                                is_def: (obj.elem.checked ? 1 : 0),
                            },
                            contentType: 'application/x-www-form-urlencoded'
                        })
                        toast.success({title: false, message: '修改成功'})
                    } catch (e) {
                        toast.error({title: false, message: e.msg})
                    }
                });
            }
        });
    }

    layui.use(['drawer','table', 'form', 'jquery', 'ztree', 'common', 'toast', 'http','dropdown'], function () {
        let table = layui.table;
        let drawer = layui.drawer;
        let form = layui.form;
        let $ = layui.jquery;
        let ztree = layui.ztree;
        let common = layui.common;
        let toast = layui.toast;
        let dropdown = layui.dropdown;
        let http = layui.http;
        let util = layui.util;
        intiCompanyList();
        reloadDeptment({});
        const bc = new BroadcastChannel('depListReload');
        bc.onmessage = function (e) {
            var treeObj = $.fn.zTree.getZTreeObj("dep");
            var nodes = treeObj.getNodesByParam("id", e.data.id, null);
            for (let node of nodes) {
                node.dep_name = e.data.dep_name;
                node.dep_no = e.data.dep_no;
                node.dep_name_and_no = e.data.dep_name + "[" + e.data.dep_no + "]";
                treeObj.updateNode(node);
            }
        };
        // select 事件
        form.on('select(company_list)', function (data) {
            var value = data.value; // 获得被选中的值
            company_list.def_company = value;
            // reloadDeptment({"pid": 0, "companyId": value});
            var zTreeObj = $.fn.zTree.getZTreeObj("dep");
            zTreeObj.destroy();
            reloadDeptment({"companyId": value});
            var curStatus = "init", curAsyncCount = 0, asyncForAll = false,
                goAsync = false;
        });
        // 右键菜单
        dropdown.render({
            elem: '.dep', // 也可绑定到 document，从而重置整个右键
            trigger: 'contextmenu', // contextmenu
            isAllowSpread: false, // 禁止菜单组展开收缩
            style: 'width: 200px', // 定义宽度，默认自适应
            data: [{
                title: '新增',
                id: 'add',
            }, {
                title: '修改',
                id: 'update',
            }, {
                title: '删除',
                id: 'del'
            }, {
                title: '刷新',
                id: 'reload'
            }, {
                title: '展开',
                id: 'expand'
            }, {
                title: '折叠',
                id: 'fold'
            }],
            click: function (obj, othis) {
                if (obj.id === 'add') {
                    window.add();
                } else if (obj.id === 'del') {
                    window.del();
                } else if (obj.id === 'update') {
                    window.edit();
                } else if (obj.id === 'reload') {
                    let treeObj = $.fn.zTree.getZTreeObj("dep");
                    var node = treeObj.getNodesByParam("id", 0, null);
                    if (node.length > 0) {
                        treeObj.reAsyncChildNodes(node[0], "refresh", false);
                    }
                    toast.success({title: false, message: '已刷新'})
                } else if (obj.id === 'expand') {
                    window.expand();
                } else if (obj.id === 'fold') {
                    window.fold();
                }
            },
            ready: function (elemPanel, elem) {
                var tagName = elem.context.activeElement.tagName;
                var treeObj = $.fn.zTree.getZTreeObj("dep");
                if (tagName == 'LI') {
                    let nodeid = elem.context.activeElement.id.replace("dep_", "");
                    var node = treeObj.getNodeByTId(nodeid);
                    treeObj.selectNode(node);
                } else {
                    // 选中根节点
                    var node = treeObj.getNodesByParam("id", 0, null);
                    if (node.length > 0) {
                        treeObj.selectNode(node[0]);
                    }
                }
                this.activeElement = elem.context.activeElement;
            }
        });
        form.on('submit(save)', function (data) {
            layer.confirm('确定要保存么', {icon: 3, title: '提示'}, async function (index) {
                layer.close(index);
                try {
                    let res_data = await common.ajax({
                        url: apiUrlConfig.department.add,
                        data: JSON.stringify(data.field)
                    })
                    toast.success({title: false, message: '保存成功'})
                    //重新加载
                    let pid = data.field.pid;
                    var treeObj = $.fn.zTree.getZTreeObj("dep");
                    //重新加载节点
                    var node = treeObj.getNodesByParam("id", pid, null);
                    if (node.length > 0) {
                        node[0].isParent = true;
                        treeObj.reAsyncChildNodes(node[0], "refresh", false);
                    }
                    layer.closeAll();
                } catch (result) {
                    if (result.status == 10001) {
                        //字段提示
                        let errorMsg = JSON.parse(result.msg);
                        for (let key in errorMsg) {
                            layer.tips(errorMsg[key], $("[name='" + key + "']").parent(), {
                                tips: [3, '#f56c6c'], time: 5000, tipsMore: true
                            });
                            console.error(key, errorMsg[key])
                        }
                    }
                }

            });
            return false;
        });
        form.on('submit(query)', function (data) {
            table.reloadData('userList', {
                where: {
                    keyword:data.field.keyword
                }
            }, true)
            return false;
        });
        table.on('toolbar(userList)', async function (obj) {
            if (obj.event === 'query') {
                drawer.open({
                    direction: "right",
                    dom: ".query",
                    distance: "30%"
                });
            }else if (obj.event === 'del') {
                let data = table.checkStatus(obj.config.id).data;
                if(data.length == 0){
                    toast.error({title:false,message:"至少选中一个人员"})
                    return
                }
                layer.confirm('确定要删除这些用户', {
                    icon: 3,
                    title: '提示'
                }, async function (index) {
                    layer.close(index);
                    try {
                        let res_data = await common.ajax({
                            url:apiUrlConfig.userMapping.delUser,
                            data:JSON.stringify(data)
                        })
                        toast.success({title:false,message:"删除成功"});
                        table.reloadData('userList', {}, true)
                    }catch (e){
                        console.log(e)
                    }
                });

            }else if (obj.event === 'add') {
                let treeObj = $.fn.zTree.getZTreeObj("dep");
                let nodes = treeObj.getSelectedNodes();
                let select_node = null;
                if (nodes.length > 0) {
                    select_node = nodes[0];
                }
                if(select_node == null){
                    toast.error({title: false, message: '双击右侧的部门树选中一个部门'})
                    return
                }
                if(select_node.id == 0){
                    toast.error({title: false, message: '请双击选中一个部门，当前选中的是公司'})
                    return
                }
                layer.open({
                    type: 2,
                    title: "给【" + select_node.dep_name + "】分配人员",
                    shade: 0.1,
                    area: ['80%', '90%'],
                    content: 'user_dic.html?id=' + select_node.id
                });
            }else if (obj.event === 'sort') {
                let treeObj = $.fn.zTree.getZTreeObj("dep");
                let nodes = treeObj.getSelectedNodes();
                let select_node = null;
                if (nodes.length > 0) {
                    select_node = nodes[0];
                }
                if(select_node == null){
                    toast.error({title: false, message: '双击右侧的部门树选中一个部门'})
                    return
                }
                if(select_node.id == 0){
                    toast.error({title: false, message: '请双击选中一个部门，当前选中的是公司'})
                    return
                }
                layer.open({
                    type: 2,
                    title: "给【" + select_node.dep_name + "】人员排序",
                    shade: 0.1,
                    area: ['80%', '90%'],
                    content: 'user_sort.html?id=' + select_node.id
                });
            }
        });
        table.on('tool(userList)', async function (obj) {
            let data = obj.data;
            if (obj.event === 'setRole') {
                layer.open({
                    type: 2,
                    title: "给【" + data.nickname + "】设置角色",
                    shade: 0.1,
                    area: ['80%', '90%'],
                    content: 'user_power.html?id=' + data.id
                });
            }
        });
    })
</script>
</body>
</html>
